import Vue from "vue";
import Vuex from "vuex";
// import axios from 'axios'
import appApi from '../../utils/api'
// import router from '../router'
Vue.use(Vuex);
export default {
    namespaced: true,
    state: {
        books: {
            Namedparent: {
                key: '2',
                name: 'ebook'
            },
            // 详情参数
            detailquery: {
                searchtitle: '',
                id: ''
            },
            // 判断加载是否完成
            loading_over: false,
            rscontype: false,
            showdetail: false,  //判断是否打开详情
            bookinfo_already_show: false,
            show_sider: false,  //是否打开侧边栏
            show_pagination: false,
            fieldsAllow: {
                sortFields: [
                    { id: "relevance", name: "相关度排序" },
                    { id: "title", name: "书名" },
                    { id: "author", name: "责任者" },
                    { id: "publisher", name: "出版社" },
                    { id: "pubYear", name: "出版日期" },
                    { id: "callNo", name: "索书号" },
                ],
                searchAdvCode: { title: "01", author: "03", publisher: "09", isbn: "05" },
                searchKeys: [
                    { "id": "", name: "任意词" },
                    { "id": "02", name: "书名" },
                    { "id": "03", name: "责任者" },
                    { "id": "04", name: "主题词" },
                    { "id": "05", name: "ISBN" },
                    { "id": "09", name: "出版社" },
                    { "id": "10", name: "丛书名" },
                    { "id": "07", name: "分类号" },
                    { "id": "08", name: "索书号" },
                ],
                sortTypes: ["desc", "asc"],
                pageSizeOptions: ['10', '20', '50', '100'],
                defaultPageSize: 20,
            },
            // qs: 请求参数
            qs: {
                Epac: {
                    arr_fieldLists: [],
                    fieldCode: '01',
                    fieldValue: '',
                    fieldValueSearchCur: '',
                    fieldConj: 'AND',
                    limiter: [],
                    sortField: "relevance",
                    sortType: "desc",
                    page: 1,
                    pageSize: 20,
                    locale: "zh_CN",
                    first: true,
                    searchWords:[
                        {
                            fieldList:[
                                {
                                    fieldCode:"title",
                                    fieldValue:"php",
                                    $$hashKey:"021" // 这一个没有使用
                                },
                                {
                                    fieldCode:"author",
                                    fieldValue:"张",
                                    fieldConj:"AND" // 这一个没有使用
                                }
                            ]
                        }
                    ]
                },
                searchWords: [{
                    fieldList: [
                        { fieldCode: "01", fieldValue: "红楼梦" }
                    ],
                }],
                filters: [
                    // {
                    //     "fieldName":"src",
                    //     "values":[
                    //         "cxstar"
                    //     ]
                    // },
                    // {
                    //     "fieldName":"pubYear",
                    //     "values":[
                    //         "2016"
                    //     ]
                    // }
                ],
                tags: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                page: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            },
            isbn: {
                searchWords: [{
                    fieldList: [{
                        fieldCode: "05",
                        fieldValue: '',
                        fieldConj: "OR"
                    }]
                }],
                filters: [],
                unionFilters: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                locale: "zh_CN",
                pageSize: 20,
                pageCount: 1
            },
            // rs:检索结果
            rs: {
                total: 180,
                content: [],
                facetsList: [{
                        "facetList": [],
                        "id": "filetype",
                        "label": "文件类型"
                    },
                    {
                        "facetList": [],
                        "id": "src",
                        "label": "电子书来源"
                    },
                    {
                        "facetList": [],
                        "id": "pub_year",
                        "label": "出版年份"
                    }
                ],

                "filters": [
                    { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
                    { "fieldName": "locationFacet", "values": ["03005"] }
                ],
                "limiter": [],
                "sortField": "relevance",
                "sortType": "desc",
                "pageSize": 20,
                "pageCount": 1,
                "locale": "zh_CN",
                "first": true,
            },

        },
    },
    mutations: {
        // 修改跳转详情参数
        ChangeDetailQuery(state, status) {
            state.books.detailquery.searchtitle = status.searchtitle;
            state.books.detailquery.id = status.id;
        },
        // 修改侧边栏打开状态
        BOOKINFO_ALREADY_SHOW(state, is_show) {
            state.books.bookinfo_already_show = is_show;
        },
        // 清空请求参数
        CLEAR_QS(state) {
            var qs = {
                Epac: {
                    "searchWords":[
                        {
                            "fieldList":[
                                {
                                    "fieldCode":"title",
                                    "fieldValue":"php",
                                    "$$hashKey":"021" // 这一个没有使用
                                },
                                {
                                    "fieldCode":"author",
                                    "fieldValue":"张",
                                    "fieldConj":"AND" // 这一个没有使用
                                }
                            ]
                        }
                    ],
                    // filters ，是左侧切面条件选择的条件
                    "filters":[
                        {
                            "fieldName":"src",
                            "values":[
                                "cxstar"
                            ]
                        },
                        {
                            "fieldName":"pubYear",
                            "values":[
                                "2016"
                            ]
                        }
                    ],
                    "limiter":[
                    ],
                    "sortField":"relevance",
                    "sortType":"desc",
                    "pageSize":3,
                    "pageCount":1,
                    "locale":"zh_CN"
                },
                searchWords: [{
                    fieldList: [
                        { fieldCode: "01", fieldValue: "红楼梦" },
                        // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                        // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                    ],
                }],
                filters: [
                    // { fieldName: "subjectFacet", values: ["红楼梦", "文学研究"] },
                    // { fieldName: "locationFacet", values: ["03005"] },
                ],
                tags: [],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                page: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            };
            state.books.qs = qs;
            state.books.rs.filters = [];
        },
        // 提交获取的过滤条件
        UpdateQsFacets(state, facetsList) {
            state.books.qs.filters = facetsList;
        },
        UpdateRsFacets(state, facetsList, indexs) {
            state.books.rs.facetsList[indexs].facetList = facetsList;
        },
        // 获取书籍总数
        UpdateRsTotal(state, total) {
            state.books.rs.total = total;
        },
        // 获取返回的书籍列表
        UpdateRsContent(state, books) {
            state.books.rs.content = books;
        },
        ///
        /**
         * 更新qs 中的检索词
         * 1、更新keyword
         * 2、这里通通重置为第1页
         * 3、
         * searchWords: [
                    {
                        fieldList: [
                            { fieldCode: "", fieldValue: "红楼梦" },
                            { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                        ],
                    }
                ],
         * @param {*} state 
         * @param {检索词，是} search_keyword 
         * 
         */
        // 获取检索词
        UpdateQsSearchKeyWord(state, search_keyword) {
            this.commit(state.books.Namedparent.name + "/UpdateQsSearchKeyWordV2", search_keyword, 1);
        },
        // 获取检索词
        UpdateQsSearchKeyWordV2(state, search_keyword, current_page) {
            // state.books.qs.searchWords[0].fieldList[0].fieldValue = search_keyword;
            state.books.qs.Epac.fieldValue = search_keyword;

            // state.books.qs.searchWords = [{
            //     fieldList: [
            //         { fieldCode: search_field_code, fieldValue: search_keyword },
            //     ],
            // }];
            state.books.qs.Epac.page = current_page;
            state.books.qs.filters = [];
        },
        //高级检索条件，多个关键词
        UpdateQsSearchFieldListAdv(state, search_field_list) {
            state.books.qs.searchWords[0].fieldList = search_field_list;
            state.books.qs.Epac.fieldValue = search_field_list[0].fieldValue;
            state.books.qs.Epac.arr_fieldLists = search_field_list;
        },
        // 年代限制 ["DT:1999/2021"] 这种格式
        UpdateQsLimiter(state, limiter) {
            state.books.qs.limiter = limiter;
            state.books.qs.Epac.limiter = limiter;
        },
        ChangeQsSearchField(state, search_field) {
            // state.books.qs.searchWords[0].fieldList[0].fieldCode = search_field;
            state.books.qs.Epac.fieldCode = search_field;
        },
        // 获取搜索词类型
        ChangeSortType(state, sortType) {
            state.books.qs.Epac.sortType = sortType;
        },
        // 获取排序
        ChangeSortField(state, sortField) {
            state.books.qs.Epac.sortField = sortField;
        },
        // 获取页码
        ChangeCurrentPage(state, currentPage) {
            state.books.qs.Epac.page = currentPage;
        },
        // 获取页码
        ChangeCurrentPageWithOutSync(state, currentPage) {
            state.books.qs.Epac.page = currentPage;
        },
        // 获取每页条数
        ChangePageSize(state, pageSize) {
            state.books.qs.pageSize = pageSize;
            state.books.rs.pageSize = pageSize;
            state.books.fieldsAllow.pageSize = pageSize;
            var current_page = state.books.qs.Epac.page;
            var total = state.books.rs.total;
            if (current_page * pageSize > total) {
                current_page = Math.ceil(total / pageSize);
                this.commit("ChangeCurrentPage", current_page);
            }
        },
        // 清空检索内容
        ClearBooksContents(state) {
            // state.books.rs.content.splice(0);
            state.books.rs.content = [];
        },
        PARAMS_INIT_QS(state, rs) {
            state.books.rs = rs;
        },
        // 详情是否打开
        SHOW_DETAIL(state, status) {
            state.books.showdetail = status;
        },
        // 获取slider
        SHOW_SIDER(state, status) {
            state.books.show_sider = status;
        },
        // 是否展示分页
        SHOW_PAGINATION(state, status) {
            state.books.show_pagination = status;
        },
        AddBook(state, {
            author,
            category,
            bisbn,
            isbn,
            pub_year,
            publisher,
            title,
            filetype,
            bookid,
            cover
        }) {
            var book = {
                author: author,
                category: category,
                bisbn: bisbn,
                isbn: isbn,
                pub_year: pub_year,
                publisher: publisher,
                title: title,
                filetype: filetype,
                bookid: bookid,
                cover: cover,
            };
            state.books.rs.content.push(book);
        },
        removeFilters(state, index) {
            // 移除弹窗
            state.dialogList.splice(index, 1);
        },
        // 获取侧边栏筛选条件
        SearchSideUpdateFilters(state, { fieldName, value }, is_search_books) {
            //数据结构 { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },

            //var filter_len = state.books.qs.filters.length;
            var findFilter = false;
            // 如果fieldName对应的fieldName如subjectFacet 是第一次添加
            state.books.qs.Epac.arr_fieldLists.forEach(function(item, i) {
                var filter = item;
                if (filter.fieldCode == fieldName) {
                    findFilter = true;
                    state.books.qs.Epac.arr_fieldLists.splice(i, 1);
                }
            });

            // for (var i = 0; i < filter_len; i++) {
            //     var filter = state.books.qs.filters[i];
            //     if (filter.fieldName == fieldName) {
            //         findFilter = true;
            //         var index = filter.values.indexOf(value);
            //         // 如果filter 中已经存在value，则之前为选中状态，现在要删除
            //         // 如果之前未选中，则现在要增加
            //         if (index >= 0) {
            //             filter.values.splice(index, 1);
            //             if (state.books.qs.filters[i].values.length == 0) {
            //                 state.books.qs.filters.splice(i, 1);
            //                 state.books.qs.Epac.arr_fieldLists.splice(i, 1);
            //             }
            //         } else {
            //             filter.values.push(value);
            //         }
            //         Vue.set(state.books.qs.filters, i, filter);
            //     }

            // }
            if (findFilter == false) {
                // state.books.qs.filters.push({ "fieldName": fieldName, "values": [value] });
                //    fieldCode: "",
                //    fieldConj: "OR",
                //    fieldValue: "",
                state.books.qs.Epac.arr_fieldLists.push({ fieldCode: fieldName, fieldValue: value, fieldConj: "AND", });
            }
            // for (i = 0; i < filter_len; i++) {
            //     if (state.books.qs.filters[i].values.length == 0) {
            //         state.books.qs.filters.splice(i, 1);
            //     }
            // }
            is_search_books = true;
            if (is_search_books) {
                this.dispatch("ebook/SearchGetBooks")
            }
        },
        // 修改加载状态
        Changeloading(state, status) {
            state.books.loading_over = status;
        }
    },
    actions: {
        // 初始化默认加载书籍列表
        GetBooks(context) {
            context.state.books.loading_over = true;
            var params = "r=epac/sr&Epac[fieldValue]=" + context.state.books.qs.Epac.fieldValue + "&Epac[fieldValueSearchCur]=" + context.state.books.qs.Epac.fieldValueSearchCur + "&Epac[fieldConj]=" + context.state.books.qs.Epac.fieldConj + "Epac[fieldCode]=" + context.state.books.qs.Epac.fieldCode;
            // 判断设备
            let flag = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            // 获取电子书列表
            appApi.EbookGetlist(encodeURIComponent(JSON.stringify(params)))
                .then(response => {
                    // axios.get(
                    //         "http://login.epac.user.kim/frontend/web/index.php?r=epac%2Febooks&q=" + encodeURIComponent(JSON.stringify(params)), {
                    //             headers: {
                    //                 //"Content-Type": "application/json",
                    //                 //   Origin: "http://localhost:8080",
                    //                 "Content-Type": "text/plain",
                    //             },
                    //         }
                    //     ).then(function(response) {
                    // if (response.data.err == true) {

                    // }
                    var data = response.data.books;
                    var x = data;
                    if (response.status == 200) {
                        if (context.state.books.rs.content.length > 0) {
                            // context.commit("ClearBooksContents");
                            context.state.books.rs.content = [];
                        }
                        var book_length = x.length;
                        var books = [];
                        for (var i = 0; i < book_length; i++) {
                            var book = {
                                id: 0,
                                title: "",
                                author: "",
                                publisher: "",
                                publish_date: "",
                                pub_year: 0,
                                cover: "",
                                intro: "",
                                isbn: "",
                                bisbn: "",
                                category: "",
                                cates: "",
                                booktype: "",
                                filetype: "",
                                bookid: "",
                                assertId: "",
                                src: "",
                                view_count: 0,
                                extid: "",
                                ext: "",
                                muluText: "",
                                created_at: 0,
                                updated_at: 0,
                                pc_read: "",
                                pc_epub: "",
                                wx_read: "",
                                wx_epub: "",
                                read: '',
                                detail: "",
                                ebooklist: []
                            };
                            book.author = x[i].author;
                            book.category = x[i].category;
                            book.cates = x[i].cates;
                            book.bisbn = x[i].bisbn;
                            book.isbn = x[i].isbn;
                            book.pub_year = parseInt(x[i].pub_year);
                            book.publish_date = x[i].publish_date;
                            book.publisher = x[i].publisher;

                            // book.src = book.src;
                            book.title = x[i].title;
                            book.id = x[i].id;
                            book.filetype = x[i].filetype;
                            book.bookid = x[i].bookid;
                            book.intro = x[i].intro;
                            book.src = x[i].src;
                            book.read = flag ? x[i].wx_read : x[i].pc_read;
                            var isbn = book.isbn;
                            if (isbn.indexOf(",") > 0) {

                                var isbns = isbn.split(",");
                                if (isbns.length > 1) {
                                    isbn = isbns[0];
                                    isbn = isbn.replace("-", "");
                                }
                            }
                            book.cover = x[i].cover;
                            books[i] = book;
                        }

                        for (let ins = 0; ins < books.length; ins++) {
                            var isbn_ = { "fieldCode": "05", fieldValue: "", "fieldConj": "OR" };
                            isbn_.fieldValue = books[ins].isbn.replace(/-/g, "");
                            context.state.books.isbn.searchWords[0].fieldList.push(isbn_)
                        }
                        context.dispatch('asyncFunc', books)
                        context.commit("SHOW_PAGINATION", true);
                        context.commit("SHOW_SIDER", true);
                        context.commit("UpdateRsTotal", parseInt(response.data.totalCount));
                    }
                    setTimeout(() => {
                        context.state.books.loading_over = false;
                    }, 1000)
                    context.state.books.rscontype = true;
                })
                .catch(function(error) {
                    // 请求失败处理
                    console.log("runoob", error);
                });
            // 获取slider filetype
            appApi.Ebookgetslider(context.state.books.qs.Epac)
                .then(res => {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].count = res.data[i].nums;
                        res.data[i].code = res.data[i].filetype;
                        res.data[i].name = res.data[i].filetype;
                    }
                    context.state.books.rs.facetsList[0].facetList = res.data;
                })
                // 获取slider 电子书来源
            appApi.Ebookgetsliderform(context.state.books.qs.Epac)
                .then(res => {
                    var src_arr = []
                    for (let i in res.data) {
                        src_arr.push(res.data[i]) //值 ['aaa' 190 'man']
                    }
                    for (var i = 0; i < src_arr.length; i++) {
                        src_arr[i].count = src_arr[i].nums;
                        src_arr[i].code = src_arr[i].src;
                        src_arr[i].name = src_arr[i].src;
                    }
                    context.state.books.rs.facetsList[1].facetList = src_arr;
                })
                // 获取slider 出版年份
            appApi.Ebookgetslideryear(context.state.books.qs.Epac)
                .then(res => {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].count = res.data[i].nums;
                        res.data[i].code = res.data[i].pub_year;
                        res.data[i].name = res.data[i].pub_year;
                    }
                    context.state.books.rs.facetsList[2].facetList = res.data;
                })
        },
        // 搜索列表
        SearchGetBooks(context) {
            context.state.books.loading_over = true;
            // 判断设备
            let flag = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            // 获取电子书列表
            appApi.NewEbookSearchGetlist(context.state.books.qs.Epac)
            .then(response => {
                var data = response.data.books;
                var x = data;
              console.log(x)
            })
            .catch(function(error) {
                // 请求失败处理
                console.log("runoob", error);
            });
            appApi.EbookSearchGetlist(context.state.books.qs.Epac)
                .then(response => {
                    var data = response.data.books;
                    var x = data;
                    if (response.status == 200) {
                        if (context.state.books.rs.content.length > 0) {
                            context.state.books.rs.content = [];
                        }
                        var book_length = x.length;
                        var books = [];
                        for (var i = 0; i < book_length; i++) {
                            var book = {
                                id: 0,
                                title: "",
                                author: "",
                                publisher: "",
                                publish_date: "",
                                pub_year: 0,
                                cover: "",
                                intro: "",
                                isbn: "",
                                bisbn: "",
                                category: "",
                                cates: "",
                                booktype: "",
                                filetype: "",
                                bookid: "",
                                assertId: "",
                                src: "",
                                view_count: 0,
                                extid: "",
                                ext: "",
                                muluText: "",
                                created_at: 0,
                                updated_at: 0,
                                pc_read: "",
                                pc_epub: "",
                                wx_read: "",
                                wx_epub: "",
                                detail: "",
                            };
                            book.author = x[i].author;
                            book.category = x[i].category;
                            book.cates = x[i].cates;
                            book.bisbn = x[i].bisbn;
                            book.isbn = x[i].isbn;
                            book.pub_year = parseInt(x[i].pub_year);
                            book.publish_date = x[i].publish_date;
                            book.publisher = x[i].publisher;

                            // book.src = book.src;
                            book.title = x[i].title;
                            book.id = x[i].id;
                            book.filetype = x[i].filetype;
                            book.bookid = x[i].bookid;
                            book.intro = x[i].intro;
                            book.src = x[i].src;
                            book.read = flag ? x[i].wx_read : x[i].pc_read;
                            var isbn = book.isbn;
                            if (isbn.indexOf(",") > 0) {

                                var isbns = isbn.split(",");
                                if (isbns.length > 1) {
                                    isbn = isbns[0];
                                    isbn = isbn.replace("-", "");
                                }
                            }
                            book.cover = x[i].cover;
                            books[i] = book;
                        }
                        for (let ins = 0; ins < books.length; ins++) {
                            var isbn_ = { "fieldCode": "05", fieldValue: "", "fieldConj": "OR" };
                            isbn_.fieldValue = books[ins].isbn.replace(/-/g, "");
                            context.state.books.isbn.searchWords[0].fieldList.push(isbn_)
                        }
                        context.dispatch('asyncFunc', books)
                        context.commit("SHOW_PAGINATION", true);
                        context.commit("SHOW_SIDER", true);
                        context.commit("UpdateRsTotal", parseInt(response.data.totalCount));
                        setTimeout(() => {
                            context.state.books.loading_over = false;
                        }, 1000)
                    }
                })
                .catch(function(error) {
                    // 请求失败处理
                    console.log("runoob", error);
                });
            // 获取slider filetype

            appApi.Ebookgetslider(context.state.books.qs.Epac)
                .then(res => {
                    // axios.post('http://login.epac.user.kim/frontend/web/index.php?r=epac%2Fcfgfiletype', context.state.books.qs.Epac).then(function(res) {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].count = res.data[i].nums;
                        res.data[i].code = res.data[i].filetype;
                        res.data[i].name = res.data[i].filetype;
                    }
                    context.state.books.rs.facetsList[0].facetList = res.data;
                })
                // 获取slider 电子书来源
            appApi.Ebookgetsliderform(context.state.books.qs.Epac)
                .then(res => {
                    var src_arr = []
                    for (let i in res.data) {
                        src_arr.push(res.data[i]) //值 ['aaa' 190 'man']
                    }
                    for (var i = 0; i < src_arr.length; i++) {
                        src_arr[i].count = src_arr[i].nums;
                        src_arr[i].code = src_arr[i].src;
                        src_arr[i].name = src_arr[i].src;
                    }
                    context.state.books.rs.facetsList[1].facetList = src_arr;
                })
                // 获取slider 出版年份
            appApi.Ebookgetslideryear(context.state.books.qs.Epac)
                .then(res => {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].count = res.data[i].nums;
                        res.data[i].code = res.data[i].pub_year;
                        res.data[i].name = res.data[i].pub_year;
                    }
                    context.state.books.rs.facetsList[2].facetList = res.data;
                })
        },
        // 电子书检索对应纸书
        asyncFunc(context, books) {
            context.state.books.isbn.searchWords[0].fieldList = context.state.books.isbn.searchWords[0].fieldList.filter(function(s) {
                return s && s.fieldValue.trim();
            });
            // context.state.books.isbn.searchWords[0].fieldList[0].fieldValue = books.books[books.ins].isbn.replace(/-/g, "");
            return new Promise((resolve) => {
                setTimeout(() => {
                    appApi.Ebookgetpagerbook(context.state.books.isbn)
                        .then(res => {
                            if (res.status == 200 && res.data) {
                                for (var i = 0; i < books.length; i++) {
                                    for (var j = 0; j < res.data.content.length; j++) {
                                        if (books[i].isbn.replace(/-/g, "") == res.data.content[j].isbn.replace(/-/g, "")) {
                                            books[i].ebooklist = res.data.content[j];

                                        }
                                    }
                                }
                                context.commit("UpdateRsContent", books);
                            }
                        })
                    resolve()
                }, 1)
            })
        }
    },
    getters: {
        // getQS: state => {
        //     return state.books.qs;
        //     // return state.books.filter(todo => todo.done)
        // }
    }
}